package com.sword.erp.stock.service;

import com.sword.erp.stock.model.Stock;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 库存服务实现类
 * @author sword
 * @date 2021/10/30 16:24
 */
@Service
@RequiredArgsConstructor
public class StockServiceImpl implements StockService {
    /**
     * redis访问对象
     */
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public Long reduceStock() {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        opsForValue.setIfAbsent("stock", "1000");

        return opsForValue.decrement("stock");
    }

    @Override
    @Cacheable(cacheNames = "testJavaBeanToRedis")
    public Stock testJavaBeanToRedis() {
        return Stock
                .builder()
                    .id(1)
                    .name("库存1")
                    .createDate(new Date())
                .build();
    }

    @Override
    @Cacheable(cacheNames = "testJavaBeanToRedisByKey", key = "#key")
    public Stock testJavaBeanToRedisByKey(String key) {
        return Stock
                .builder()
                .id(2)
                .name("库存2")
                .createDate(new Date())
                .build();
    }

    @Override
    @Cacheable(cacheNames = "testJavaBeanListToRedis")
    public List<Stock> testJavaBeanListToRedis() {
        List<Stock> stockList = new ArrayList<>();
        stockList.add(Stock
                .builder()
                .id(3)
                .name("库存3")
                .createDate(new Date())
                .build());

        stockList.add(Stock
                .builder()
                .id(4)
                .name("库存4")
                .createDate(new Date())
                .build());

        return stockList;
    }
}
